<?php
//定义分隔符
define('DS', DIRECTORY_SEPARATOR);
//定义root path
define('ROOT', dirname(__FILE__) . DS);
require('./class/AutoLoader.php');
spl_autoload_register('Autoloader::load');

//set path
Autoloader::$directory = ROOT;
Autoloader::$paths = array('./class/', './rsa/', './model/', './service/', './lib/', './config/', '../sdk/');
header("Content-Type: application/json; charset=utf-8");
$tmp = @explode('?', $_SERVER['REQUEST_URI']);
$tmp = @explode('/', $tmp[0]);
$resource = $tmp[1];
$id = count($tmp) > 2 ? $tmp[2] : '';
// add log
$log_dir = sys_get_temp_dir().'/ziyan/';
if (!file_exists($log_dir)) {
    mkdir($log_dir);
}
$log_file = sys_get_temp_dir().'/ziyan/' . $resource . '-' . date('Ymd') . '.txt';
$log_data = array(
    'request_time' => date('Y-m-d H:i:s'),
    'request_uri' => isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '',
    'resource_id' => $id,
);
//引入config文件
define("ROOT_PATH", __DIR__ . "/");
define("APP_NAME", "rest");
define('CONFIG_PATH', json_encode(array(
        ROOT_PATH . '../sdk/Config/',
    ))
);
//结束

// add version
if (isset($_REQUEST['v']) && intval($_REQUEST['v']) != 0) {
    $version = $_REQUEST['v'];
} else {
    $version = 1;
}

if (empty($resource)) {
    printResult('', 'require resource');
} else {
    @parse_str($_SERVER['QUERY_STRING'], $query);
    $post = @file_get_contents("php://input");
    $method = strtolower($_SERVER['REQUEST_METHOD']);
    $log_data['req_body'] = json_encode($query);
    $log_data['post_body'] = json_encode($post);
    $log_data['method'] = $method;

    $file = './service/V' . $version . '/' . $resource . '.php';
    if (!file_exists($file)) {
        printResult('', 'resource not exists');
    } else {
        $class = '\\V'.$version.'\\'.$resource;
        $obj = new $class();
        $query['id'] = $id;
        /*
         * 微信回调地址不能用 parse_str
         */
        if($resource != 'WxPayCallback'){
            @parse_str($post, $post);
        }
        if (array_key_exists('payload', $post)) {
            $post['payload'] = str_replace(' ', '+', $post['payload']);
        }
        $result = array();
        $errorMsg = $obj->$method($query, $post, $result);
        printResult($result, $errorMsg);
    }
}


function printResult($result, $ErrorMsg,$error_code=9999)
{
    $data['Success'] = 1;
    $data['ErrorCode'] = 0;
    $data['ErrorMsg'] = $ErrorMsg;
    $data['CallInfo'] = filteNull($result);
    $data['CallInfo'] = $result;
    if (!empty($ErrorMsg)) {
        $data['Success'] = -1;
        $errorCode = array(
            'require resource' => 1000,
            'resource not exists' => 1001,
            'require payload' => 1002,
            'method not implemented' => 1003,
            'require user id' => 2000,
            'sign wrong' => 403,
            'essential data required' => 2001,
            'data illegal' => 2002,
            'require resource id' => 2003,
            'user not exists' => 3001,
            'wrong password' => 3002,
            'Have no product or product is under the shelf' => 4001,
            'AGAIN_PRE_PAY' => '10000',
        );
        if (array_key_exists($ErrorMsg, $errorCode)) {
            $data['ErrorCode'] = $errorCode[$ErrorMsg];
        } else {
            $data['ErrorCode'] = $error_code;
        }
    }
    echo json_encode($data);
    // add log
    global $log_file;
    global $log_data;
    $log_data['response'] = json_encode($data);
    $log_data['finish_time'] = date('Y-m-d H:i:s');
    file_put_contents($log_file, json_encode($log_data) . "\n", FILE_APPEND);
    global $track_log_data;
    $track_log_data['sid'] = isset($_GET['sid']) ? $_GET['sid'] : 0; // 来源
    $track_log_data['pid'] = isset($_GET['pid']) ? $_GET['pid'] : 0; // 页面id
    $track_log_data['resource'] = isset($_GET['resource']) ? $_GET['resource'] : 0; //请求资源
    $track_log_data['uid'] = isset($_GET['customer_id']) ? $_GET['customer_id'] : 0; // 用户id
    $track_log_data['guid'] = isset($_GET['guid']) ? $_GET['guid'] : 0; // 唯一识别码
//    insertTrackLog($track_log_data);
    exit;
}

// 过滤 undefind ,null
function filteNull($data)
{
    $json = $data;
    if (is_array($data)) {
        foreach ($data as $key => $item) {
            $json[$key] = filteNull($item);
        }
    } elseif (is_object($data)) {
        foreach ($data as $key => $item) {
            $json->$key = filteNull($item);
        }
    } else {
        if ($data == 'null' || $data == null || $data == 'undefined') {
            $json = '';
        }
    }
    return $json;
}

function getRedisConfig()
{
    $redis_config['host'] = \Util\Config::get('host','Redis');
    $redis_config['port'] = \Util\Config::get('port','Redis');
    $redis_config['auth'] = \Util\Config::get('auth','Redis');
    return $redis_config;
}

function insertTrackLog($track_log_data)
{
    $track_log_orm = new \Orm\TrackLog\TrackLogClass();
    $track_log_orm['sid'] = $track_log_data['sid'];
    $track_log_orm['pid'] = $track_log_data['pid'];
    $track_log_orm['resource'] = $track_log_data['resource'];
    $track_log_orm['uid'] = $track_log_data['uid'];
    $track_log_orm['guid'] = $track_log_data['guid'];
    $track_log_orm->insert();
}